<template>
  <div class="wrapper">
    <a-page-header
      style="padding: 12px;border: 1px solid rgb(235, 237, 240)"
      title="指标列表"
      @back="() => $router.go(-1)"
    />
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键字">
                <a-input v-model="queryParam.target" placeholder="请输入指标名称" @keyup.enter.native="getTreeData"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="getTreeData">查询</a-button>
                <a-button style="margin-left: 8px" @click="setEmpty">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <span style="margin-right: 16px;">已选中{{ selectedRowKeys.length }}行</span>
        <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
        <a-button icon="delete" @click="handleDeleteBatch">删除</a-button>
      </div>
      <a-spin :spinning="loading">
        <a-table
          v-if="quotaData && quotaData.length > 0"
          ref="table"
          size="default"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="quotaData"
          :rowSelection="rowSelection"
          :pagination="false"
          childrenColumnName="childs"
          :defaultExpandAllRows="true"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="mustFlag" slot-scope="text">
            {{ text === 0 ? '否' : text === 1 ? '是' : '' }}
          </span>
          <span slot="comment" slot-scope="text">
            <ellipsis :length="10" tooltip>{{ text }}</ellipsis>
          </span>
          <span slot="backUpData" slot-scope="text">
            <ellipsis :length="10" tooltip>{{ text }}</ellipsis>
          </span>
          <span slot="files" slot-scope="text">
            <div :key="item.id" v-for="item in text">
              <!-- <a :href="item.url" target="_black" :download="item.original">{{ item.original }}</a> -->
              <a @click="$fileDownLoad(item)">
                <ellipsis :length="10" tooltip>{{ item.original }}</ellipsis>
              </a>
            </div>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleCheck(record)" v-if="record.cj === 4">查看</a>
              <a-divider type="vertical" v-if="record.cj === 4" />
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleDelete(record)">删除</a>
              <a-divider type="vertical" v-if="record.cj !== 4" />
              <a @click="handleAddSub(record)" v-if="record.cj !== 4">新增子项</a>
              <a-divider type="vertical" v-if="record.cj === 1 || record.cj === 4"/>
              <a @click="handleAssign(record)" v-if="record.cj === 1 || record.cj === 4">指派人员</a>
            </template>
          </span>
        </a-table>
        <div v-else>
          <a-empty v-if="!loading" />
        </div>
      </a-spin>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :treeData="treeData"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <check-form
        :treeData="treeData"
        ref="checkModal"
      />
      <assign
        ref="assignModal"
      />
    </a-card>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getQuotaTree, saveQuota, deleteQuota } from '@/api/category'

import CreateForm from './CreateForm'
import CheckForm from './CheckForm'
import Assign from './Assign'

const columns = [
  {
    title: '列表序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '指标',
    dataIndex: 'target'
  },
  {
    title: '排序',
    dataIndex: 'sort'
  },
  {
    title: '序号',
    dataIndex: 'serialNumber'
  },
  {
    title: '总分',
    dataIndex: 'totalPoint'
  },
  {
    title: '是否必须',
    dataIndex: 'mustFlag',
    scopedSlots: { customRender: 'mustFlag' }
  },
  {
    title: '说明',
    dataIndex: 'comment',
    scopedSlots: { customRender: 'comment' }
  },
  {
    title: '备查资料',
    dataIndex: 'backUpData',
    scopedSlots: { customRender: 'backUpData' }
  },
  {
    title: '考核资料',
    dataIndex: 'files',
    scopedSlots: { customRender: 'files' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '260px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'DeclareCategoryQuota',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    CheckForm,
    Assign
  },
  data () {
    this.columns = columns
    return {
      socialOrganizationTypeId: this.$route.query.socialOrganizationTypeId,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {},
      quotaData: [],
      treeData: [],
      selectedRowKeys: [],
      loading: false
    }
  },
  watch: {
    '$route.query.socialOrganizationTypeId': {
      handler (val) {
        if (val && +val !== +this.socialOrganizationTypeId) {
          document.querySelector('html').scrollTop = 0
          this.socialOrganizationTypeId = val
          this.queryParam = {}
          this.treeData = []
          this.quotaData = []
          this.selectedRowKeys = []
          this.getTreeData()
        }
      },
      deep: true
      }
  },
  filters: {
  },
  created () {
  },
  deactivated () {
    this.visible = false
  },
  mounted () {
    this.getTreeData()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    setEmpty () {
      this.queryParam = {}
      this.getTreeData()
    },
    getTreeData () {
      this.loading = true
      const requestParameters = Object.assign({}, this.queryParam)
      requestParameters.socialOrganizationTypeId = this.socialOrganizationTypeId
      getQuotaTree(requestParameters)
          .then(res => {
            const data = this.getLeaf(res)
            this.treeData = [{
              id: 0,
              target: '无',
              childs: data
            }]
            this.quotaData = data
          }).finally(() => {
              this.loading = false
          })
    },
    getLeaf (data) {
      for (let i = 0, len = data.length; i < len; i++) {
        if (data[i].cj === 3) {
          data[i].isLeaf = true
        }
        if (data[i].cj === 4) {
          data[i].disabled = true
        } else if (data[i].childs && data[i].childs.length > 0) {
          data[i].childs = this.getLeaf(data[i].childs)
        }
      }
      return data
    },
    handleDeleteBatch () {
      if (this.selectedRowKeys.length === 0) {
        this.$warning({
          title: '提示',
          content: '请选择需要删除的数据'
        })
      } else {
        console.log(this.selectedRowKeys)
        deleteQuota({
            id: this.selectedRowKeys.join(',')
          }).then(res => {
              // 刷新表格
              this.getTreeData()
              this.$message.success('批量删除成功')
            })
      }
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleAddSub (record) {
      this.mdl = { parentId: record.id, disabled: record.isLeaf, sub: true }
      this.visible = true
    },
    handleEdit (record) {
      let assessmentList = []
      if (record.files) {
        assessmentList = record.files.map(item => {
          const { id, original, url } = item
          return {
            uid: id,
            name: original,
            status: 'done',
            url: url
          }
        })
      }
      this.mdl = { ...record, assessmentList }
      this.visible = true
    },
    handleCheck (record) {
      this.$refs.checkModal.checkView(record)
    },
    handleDelete (record) {
      this.$confirm({
        title: '删除确认',
        content: '确认要删除该数据吗？并且不可恢复！',
        okType: 'danger',
        onOk: () => {
          deleteQuota({
            id: record.id
          }).then(res => {
              // 刷新表格
              this.getTreeData()
              this.$message.success('删除成功')
            })
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          values.socialOrganizationTypeId = this.socialOrganizationTypeId
          values.fileIds = values.assessmentList && values.assessmentList.length > 0 ? values.assessmentList.map(item => item.uid) : []
          delete values.assessmentList
          saveQuota(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.getTreeData()

              this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleAssign (record) {
      if (record.cj === 4) {
        this.$refs.assignModal.assignView([record.id])
      } else if (record.childs && record.childs.length > 0) {
        const ids = this.getLeafId(record.childs)
        this.$refs.assignModal.assignView(ids)
      }
    },
    getLeafId (data) {
      let arr = []
      for (let i = 0, len = data.length; i < len; i++) {
        if (data[i].cj === 4) {
          arr.push(data[i].id)
        } else if (data[i].childs && data[i].childs.length > 0) {
          arr = [...arr, ...this.getLeafId(data[i].childs)]
        }
      }
      return arr
    }
  }
}
</script>

<style lang="less" scoped>
.wrapper {
  background: #fff;
}
</style>
